package com.bdqn.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import com.alibaba.fastjson.JSON;
import com.bdqn.common.EmailUtil;
import com.bdqn.common.MD5Util;
import com.bdqn.common.PageUtil;
import com.bdqn.pojo.Account;
import com.bdqn.pojo.Comment;
import com.bdqn.pojo.RoomType;
import com.bdqn.service.AccountService;
import com.bdqn.service.CommentService;
import com.bdqn.service.RoomTypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * 前台首页控制器
 *
 * @author Administrator
 */

@Controller
@RequestMapping("/home")
public class HomeController {

    @Resource
    private RoomTypeService roomTypeService;

    @Resource
    private AccountService accountService;

    @Resource
    private CommentService commentService;


    @RequestMapping("home/account")
    public String rooms(Model model) {
        return "room1";
    }


    @GetMapping("/index")
    public ModelAndView index(ModelAndView model) {
        model.setViewName("home/index/index");
        return model;
    }


    /**
     * 分页查询房间类型数据
     *
     * @param offset
     * @return
     */
    @GetMapping("/ajaxPage")
    @ResponseBody
    public String ajaxPage(@RequestParam(name = "offset", defaultValue = "0") Integer offset) {
        System.out.println("/*/*/*/*/*/*/*/*" + offset);
        int pageSize = 6; // 页大小

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("offset", offset);
        queryMap.put("pageSize", pageSize);

        // 查询总记录数
        int record = roomTypeService.getTotal(queryMap);
        PageUtil<RoomType> pageUtill = new PageUtil<>(offset, pageSize, record);
        if (offset > pageUtill.getEndIndex()) {
            queryMap.put("offset", pageUtill.getEndIndex());
        }
        List<RoomType> pageList = roomTypeService.findList(queryMap);
        pageUtill.setList(pageList);

        // 列表数据
        String dataRowStr = "";
        for (RoomType roomType : pageList) {
            dataRowStr += "\t\t<div class=\"col-md-4 col-sm-6\">\n" +
                    "\t\t\t<div id=\"serv_hover\"  class=\"room\">\n" +
                    "\t\t\t\t<div class=\"room_img\">\n" +
                    "\t\t\t\t\t<figure> <a href=\"/home/account/book_order?roomTypeId=" + roomType.getId() + "\"><img src=\"../../../../" + roomType.getPhoto() + "\" class=\"img-responsive\" alt=\"PLuxury Room\" title=\"Luxury Room\"></a></figure>\n" +
                    "\t\t\t\t</div>\n" +
                    "\t\t\t\t<div class=\"bed_room\">\n" +
                    "\t\t\t\t\t<h4 class=\"sky-h4\"><a href=\"/home/account/book_order?roomTypeId==" + roomType.getId() + "\">" + roomType.getName() + "</a></h4>\n" +
                    "\t\t\t\t\t<h4 class=\"price\"><a href=\"/home/account/book_order?roomTypeId==" + roomType.getId() + "\">" + roomType.getPrice() + "/ 每晚</a></h4>\n" +
                    "\t\t\t\t</div>\n" +
                    "\t\t\t</div>\n" +
                    "\t\t</div>\n";
        }

        String pageUtilStartStr = "<ul id=\"pageUtils\" class=\"pagination\">\t<li><a href=\"javascript:getRoomTypePage(1);\" id=\"firstPage\">首页</a></li>\n" +
                "\t<li><a href=\"javascript:getRoomTypePage(1);\" id=\"two\">1</a></li>\n" +
                "\t<li><a href=\"javascript:getRoomTypePage(2);\" id=\"three\">2</a></li>\n";

        String pageUtilEndStr = "\t<li><a href=\"javascript:getRoomTypePage(" + pageUtill.getTotalPage() + ");\" id=\"totalPage\">尾页</a></li>\n" +
                "\t<li><a href=\"javascript:void(0);\">当前页为：" + pageUtill.getCurrentPage() + "</a></li>" +
                "\n</ul>";

        String pageUtilMiddleStr = "\t\t<li><a href=\"javascript:void(0);\" id=\"three\">。。。</a></li>\n" +
                "\t\t<li><a href=\"javascript:getRoomTypePage(" + (pageUtill.getTotalPage() - 1) + ");\" id=\"four\">" + (pageUtill.getTotalPage() - 2) + "</a></li>\n" +
                "\t\t<li><a href=\"javascript:getRoomTypePage(" + pageUtill.getTotalPage() + ");\" id=\"five\">" + pageUtill.getTotalPage() + "</a></li>\n";

        String pageUtilStr = pageUtilStartStr;
        if ((pageUtill.getTotalPage() != 2)) {
            pageUtilStr += pageUtilMiddleStr;
        }
        pageUtilStr += pageUtilEndStr;

        String resultStr = dataRowStr + pageUtilStr;
        System.out.println(resultStr);
        return resultStr;
    }


    @RequestMapping("account/book_order")
    public String room(Model model,Long roomTypeId){
        model.addAttribute("roomType",roomTypeService.getroom(roomTypeId));
//        model.addAttribute("accountList",accountService.acoountList(roomTypeId));
        List<Comment> list = commentService.commentList(roomTypeId);
        System.out.println(roomTypeId + " -------------- " + list.size());
        model.addAttribute("commentList", commentService.commentList(roomTypeId));
        return "/home/account/room";

    }





    /**
     * 跳转前台登录页面
     *
     * @return
     */
    @RequestMapping("/login2")
    public String login2() {
        System.out.println("跳转前台登录页面");
        return "home/index/login2";
    }

    /**
     * 前端登录信息提交
     *
     * @param account
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String loginAct(Account account, String vcode, HttpServletRequest request) {
        System.out.println("进入");

        Map<String, String> retMap = new HashMap<String, String>();
        if (account == null) {
            retMap.put("type", "error");
            retMap.put("msg", "请填写正确的用户信息！");
            return JSON.toJSONString(retMap);
        }
        if (StringUtils.isEmpty(account.getName())) {
            retMap.put("type", "error");
            retMap.put("msg", "用户名不能为空！");
            return JSON.toJSONString(retMap);
        }
        if (StringUtils.isEmpty(account.getPassword())) {
            retMap.put("type", "error");
            retMap.put("msg", "密码不能为空！");
            return JSON.toJSONString(retMap);
        }
        if (StringUtils.isEmpty(vcode)) {
            retMap.put("type", "error");
            retMap.put("msg", "验证码不能为空！");
            return JSON.toJSONString(retMap);
        }
        Object attribute = request.getSession().getAttribute("accountLoginCpacha");
        if (attribute == null) {
            retMap.put("type", "error");
            retMap.put("msg", "验证码过期，请刷新！");
            return JSON.toJSONString(retMap);
        }
        if (!vcode.equalsIgnoreCase(attribute.toString())) {
            retMap.put("type", "error");
            retMap.put("msg", "验证码错误！");
            return JSON.toJSONString(retMap);
        }
        Account findByName = accountService.findByName(account.getName());
        if (findByName == null) {
            System.out.println("用户名不存在");
            retMap.put("type", "error");
            retMap.put("msg", "用户名不存在！");
            return JSON.toJSONString(retMap);
        }
        if (!MD5Util.md5Password(account.getPassword()).equals(findByName.getPassword())) {
            System.out.println("密码错误");
            retMap.put("type", "error");
            retMap.put("msg", "密码错误！");
            return JSON.toJSONString(retMap);
        }
        if (findByName.getStatus() == -1) {
            retMap.put("type", "error");
            retMap.put("msg", "该用户已被禁用，请联系管理员！");
            return JSON.toJSONString(retMap);
        }
        request.getSession().setAttribute("account", findByName);
        request.getSession().setAttribute("accountLoginCpacha", null);
        retMap.put("type", "success");
        retMap.put("msg", "登录成功！");
        return JSON.toJSONString(retMap);
    }


    /**
     * 登录信息提交
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/czpad", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> resetpassword(
            @RequestParam(name = "NameAndMobile", defaultValue = "") String NameAndMobile,
            @RequestParam(name = "Email", defaultValue = "") String Email, HttpServletRequest request) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        //验证是否存在‘#’并且只有一个
        if (NameAndMobile.indexOf('#') > -1 && (NameAndMobile.indexOf('#') == NameAndMobile.lastIndexOf('#'))) {
            //取各段值
            String[] buff = NameAndMobile.split("#");
            queryMap.put("name", buff[0]);
            queryMap.put("mobile", buff[1]);
            List<Account> findList = accountService.findList(queryMap);
            if (Email.length() == 0) {
                if (findList.size() < 1) {
                    queryMap.put("type", "error");
                    queryMap.put("msg", "用户不存在，请重新填写！");
                    return queryMap;
                }
            } else {
                //正则表达邮箱格式
                String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
                Pattern p = Pattern.compile(regEx1);
                Matcher m = p.matcher(Email);
                if (!m.matches()) {
                    queryMap.put("type", "error");
                    queryMap.put("msg", "邮箱输入格式有误，请重新填写！");
                    return queryMap;
                }
            }

        } else {
            queryMap.put("type", "error");
            queryMap.put("msg", "输入格式有误，请重新填写！");
            return queryMap;
        }
        //随机产生一个6位混合密码
        if (Email.length() != 0) {
            String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            Random random = new Random();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 6; i++) {
                int number = random.nextInt(62);
                sb.append(str.charAt(number));
            }
            String[] buff = NameAndMobile.split("#");
            Account account = accountService.findByName(buff[0]);
            account.setPassword(MD5Util.md5Password(sb.toString()));
            if (accountService.edit(account) <= 0) {
                queryMap.put("type", "error");
                queryMap.put("msg", "修改失败，请联系管理员！");
                return queryMap;
            }
            //发送邮箱
            EmailUtil se = new EmailUtil();
            se.doSendHtmlEmail("酒店管理系统重置密码", "您的密码重置为：" + sb.toString() + "为账号安全尽快改密码。", Email);
            queryMap.put("type", "success");
            queryMap.put("msg", "重置成功，请通过邮箱查收！");
        }
        return queryMap;

    }


    /**
     * 注册信息提交
     *
     * @param account
     * @return
     */
    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    @ResponseBody
    public String regAct(Account account) {
        Map<String, String> retMap = new HashMap<String, String>();
        if (account == null) {
            retMap.put("type", "error");
            retMap.put("msg", "请填写正确的用户信息！");
            return JSON.toJSONString(retMap);
        }
        if (StringUtils.isEmpty(account.getName())) {
            retMap.put("type", "error");
            retMap.put("msg", "用户名不能为空！");
            return JSON.toJSONString(retMap);
        }
        if (StringUtils.isEmpty(account.getPassword())) {
            retMap.put("type", "error");
            retMap.put("msg", "密码不能为空！");
            return JSON.toJSONString(retMap);
        }
        if (StringUtils.isEmpty(account.getMobile())) {
            retMap.put("type", "error");
            retMap.put("msg", "手机号不能为空！");
            return JSON.toJSONString(retMap);
        }
        if (account.getMobile().length() != 13 && Long.parseLong(account.getMobile()) < 999999999) {
            retMap.put("type", "error");
            retMap.put("msg", "手机号格式错误，请输入13位数字字符");
            return JSON.toJSONString(retMap);
        }
        if (isExist(account.getName())) {
            retMap.put("type", "error");
            retMap.put("msg", "该用户名已经存在！");
            return JSON.toJSONString(retMap);
        }
        account.setRealName(" ");
        account.setIdCard(" ");
        account.setAddress(" ");
        if (accountService.add(account,0) <= 0) {
            retMap.put("type", "error");
            retMap.put("msg", "注册失败，请联系管理员！");
            return JSON.toJSONString(retMap);
        }
        retMap.put("type", "success");
        retMap.put("msg", "注册成功！");
        return JSON.toJSONString(retMap);
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        request.getSession().setAttribute("account", null);
        return "redirect:login2";
    }


    private boolean isExist(String name) {
        Account account = accountService.findByName(name);
        if (account == null)
            return false;
        return true;
    }

}
